/**
 * 
 */
package pipecleaner.agent.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Executes a local process synchronously.
 *
 * @author J. Michael McGarr
 */
public class SynchronousProcessExecutor implements ProcessExecutor {

	
	public Output call (String command) throws FailedCommandException {
		Output output = null;
		if (commandExists(command)) {
			output = callCommand(command);
		}
		return output;
	}

	private Output callCommand(String command) throws FailedCommandException {
		InputStreamReader inputStream = null;
		BufferedReader input = null;
		int returnCode = -1;
		StringBuffer output = new StringBuffer();
		String line = "";
		
		try {			
			Runtime runtime = Runtime.getRuntime();
			Process process = runtime.exec(command);
			returnCode = process.waitFor();
            inputStream = new InputStreamReader(process.getInputStream());
            input = new BufferedReader(inputStream);
            while ((line = input.readLine()) != null) {
                output.append(line);
//                output.append("<br/>");
            }
			
		} catch (Exception e) {
            throw new FailedCommandException("Unable to execute the command [" + command + "]", e);
		} finally {
			try {
				if (inputStream != null) inputStream.close();
				if (input != null) input.close();
			} catch (IOException e) {
				// do nothing
			}
		}
		
		return new Output(returnCode, output.toString());
	}

	private boolean commandExists(String command) {
		return true;
	}

}
